<template>
  <div class="descriptor-editor">
    <div class="descriptor-list">
      <el-card
        v-for="(descriptor, index) in descriptors"
        :key="index"
        class="descriptor-card theme-default"
      >
        <div class="card-content">
          <span
            class="delete-icon"
            title="删除"
            @click="removeDescriptor(index)"
          >
            <el-icon><Close /></el-icon>
          </span>
          
          <!-- 编辑模式 -->
          <div v-if="editingDescriptor === index" class="descriptor-edit-mode">
            <div class="edit-header">
              <span class="edit-title">编辑变量值</span>
              <div class="edit-actions">
                <el-button size="small" type="primary" @click="saveDescriptorEdit(index)">保存</el-button>
                <el-button size="small" @click="cancelDescriptorEdit()">取消</el-button>
              </div>
            </div>
            <div class="edit-variables">
              <div v-for="(variable, varIndex) in getDescriptorVariables(descriptor)" :key="varIndex" class="edit-variable-item">
                <el-input
                  v-model="editingVariableValues[variable.name]"
                  :placeholder="`请输入 ${variable.name} 的值`"
                  size="small"
                >
                  <template #prepend>
                    <el-tag size="small" type="info">{{ variable.name }}</el-tag>
                  </template>
                </el-input>
              </div>
            </div>
          </div>
          
          <!-- 显示模式 -->
          <span v-else class="descriptor-contrast" v-html="highlightDescriptorWithEdit(descriptor, index)"></span>
          

        </div>
      </el-card>
    </div>

    <div class="add-descriptor">
      <div class="add-input-group">
        <el-autocomplete
          v-model="newDescriptor"
          :fetch-suggestions="fetchSuggestions"
          placeholder="输入或选择 x-descriptor"
          :trigger-on-focus="true"
          @select="handleSelect"
          @input="handleInput"
          @keyup.enter="handleEnterKey"
          value-key="template"
          popper-class="descriptor-autocomplete-popper"
          class="autocomplete-input"
          clearable
        >
          <template #default="{ item }">
            <!-- 分组分隔线 -->
            <div v-if="item.isFirstInGroup" class="group-divider">
              <span class="group-name">{{ item.groupDisplayName }}</span>
            </div>
            <!-- 选项内容 -->
            <div class="autocomplete-option" :class="{ 
              'has-variables': hasVariables(item),
              'group-item': true 
            }">
              <div class="option-header">
                <div class="option-template" v-html="formatTemplate(item.template, item.variables)"></div>
                <div class="option-badges">
                  <el-tag v-if="hasVariables(item)" size="small" type="warning" class="variable-badge">
                    <el-icon><Edit /></el-icon>
                    {{ item.variables.length }} 变量
                  </el-tag>
                  <el-tag size="small" type="success" effect="light" class="group-badge">
                    {{ item.group }}
                  </el-tag>
                </div>
              </div>
              <div v-if="hasVariables(item)" class="variables-display">
                <span class="variables-label">变量：</span>
                <span class="variables-list">
                  <el-tag 
                    v-for="variable in item.variables" 
                    :key="variable" 
                    size="small" 
                    type="info" 
                    class="variable-tag"
                  >
                    {{ variable }}
                  </el-tag>
                </span>
              </div>
              <div class="option-desc">{{ item.desc }}</div>
            </div>
          </template>
        </el-autocomplete>
        <el-button 
          @click="addDescriptor" 
          type="primary" 
          :disabled="!canAddDescriptor"
          :loading="false"
        >
          添加
        </el-button>
      </div>
    </div>
    
    <!-- 变量编辑区域 -->
    <div v-if="selectedOption && selectedOption.variables && selectedOption.variables.length > 0" class="variable-editor">
      <div class="variable-editor-header">
        <div class="header-title">
          <el-icon><Edit /></el-icon>
          <span>变量设置</span>
        </div>
        <el-button 
          size="small" 
          type="danger" 
          :icon="Close" 
          @click="clearSelection"
          title="清除当前选择"
        >
          清除
        </el-button>
      </div>
      <div class="variable-form">
        <div class="variable-preview">
          <span class="preview-label">预览：</span>
          <code class="preview-content" v-html="generatePreview()"></code>
          <div class="preview-status">
            <el-tag 
              v-if="canAddDescriptor" 
              type="success" 
              size="small"
              effect="light"
            >
              ✓ 可以添加
            </el-tag>
            <el-tag 
              v-else 
              type="warning" 
              size="small"
              effect="light"
            >
              请填写所有变量
            </el-tag>
          </div>
        </div>
        <div class="variable-inputs">
          <div v-for="variable in selectedOption.variables" :key="variable" class="variable-input-item">
            <el-form-item class="variable-form-item">
              <el-input
                v-model="variableValues[variable]"
                :placeholder="`请输入 ${variable} 的值`"
                @input="updatePreview"
                class="variable-input"
              >
                <template #prepend>
                  <el-tag size="small" type="info">{{ variable }}</el-tag>
                </template>
              </el-input>
            </el-form-item>
          </div>
        </div>
      </div>
    </div>
    
    <div v-if="selectedOption" class="descriptor-desc">
      <div class="desc-item">
        <span class="desc-label">说明：</span>
        <span class="desc-content">{{ selectedOption.desc }}</span>
      </div>
      <div v-if="selectedOption.example" class="desc-item">
        <span class="desc-label">示例：</span>
        <code class="desc-example">{{ selectedOption.example }}</code>
      </div>
    </div>

    <div class="dialog-footer">
      <el-button @click="$emit('cancel')">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleSave"
      >
        <el-icon v-if="selectedOption || newDescriptor.trim()"><WarningFilled /></el-icon>
        {{ selectedOption || newDescriptor.trim() ? '保存所有更改' : '保存' }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import xDescriptorOptions from '@/assets/options/x-descriptors_options.json'
import { Close, Edit, WarningFilled } from '@element-plus/icons-vue'

interface DescriptorOption {
  key: string
  desc: string
  type: string[]
  group: string
  template: string
  variables?: string[]
  example?: string
}

const props = defineProps<{
  field: {
    x_descriptors: string[]
    path?: string
    label?: string
  }
}>()

const emit = defineEmits<{
  (e: 'save', field: any): void
  (e: 'cancel'): void
  (e: 'syncFieldGroup', fieldPath: string, action: 'add' | 'remove'): void
}>()

const descriptors = ref<string[]>([...props.field.x_descriptors])
const newDescriptor = ref('')
const options = ref<DescriptorOption[]>(xDescriptorOptions as DescriptorOption[])
const selectedOption = ref<DescriptorOption | null>(null)
const variableValues = reactive<Record<string, string>>({})

// 编辑已存在描述符的状态
const editingDescriptor = ref<number | null>(null)
const editingVariableValues = reactive<Record<string, string>>({})

// 分组过滤选项 - 只返回实际可选的选项，分组用于样式展示
const groupedOptions = computed(() => {
  let filtered = options.value
  
  if (newDescriptor.value) {
    const query = newDescriptor.value.toLowerCase()
    filtered = options.value.filter(opt =>
      opt.key.toLowerCase().includes(query) ||
      opt.desc.toLowerCase().includes(query) ||
      opt.template.toLowerCase().includes(query) ||
      opt.group.toLowerCase().includes(query)
    )
  }
  
  // 按组分类
  const grouped = filtered.reduce((acc, option) => {
    const group = option.group || '其他'
    if (!acc[group]) {
      acc[group] = []
    }
    acc[group].push(option)
    return acc
  }, {} as Record<string, DescriptorOption[]>)
  
  // 定义组的显示顺序
  const groupOrder = [
    '基础输入组件',
    '选择组件',
    'Kubernetes资源组件',
    'Kubernetes策略组件',
    '布局和分组组件',
    '状态显示组件',
    '描述和标签组件',
    '其他'
  ]
  
  // 只返回实际的选项，不包含分组标题
  const result: any[] = []
  groupOrder.forEach(groupName => {
    if (grouped[groupName] && grouped[groupName].length > 0) {
      // 为每个选项添加分组信息用于样式显示
      const groupItems = grouped[groupName].map(item => ({
        ...item,
        isFirstInGroup: result.length === 0 || result[result.length - 1].group !== groupName,
        groupDisplayName: groupName
      }))
      result.push(...groupItems)
    }
  })
  
  return result
})

// 监听选中的选项，重置变量值
watch(selectedOption, (newOption) => {
  // 清空之前的变量值
  Object.keys(variableValues).forEach(key => {
    delete variableValues[key]
  })
  
  // 初始化新变量值
  if (newOption && newOption.variables) {
    newOption.variables.forEach(variable => {
      variableValues[variable] = ''
    })
  }
}, { immediate: true })

const fetchSuggestions = (_query: string, cb: (results: any[]) => void) => {
  cb(groupedOptions.value)
}

const hasVariables = (option: DescriptorOption) => {
  return option.variables && option.variables.length > 0
}





const generatePreview = () => {
  if (!selectedOption.value || !selectedOption.value.variables) {
    return selectedOption.value?.template || ''
  }

  let preview = selectedOption.value.template
  selectedOption.value.variables.forEach(variable => {
    const value = variableValues[variable]
    const regex = new RegExp(`\\{${variable}\\}`, 'g')
    if (value && value.trim() !== '') {
      preview = preview.replace(regex, `<span class="variable-filled">${value}</span>`)
    } else {
      preview = preview.replace(regex, `<span class="variable-empty">{${variable}}</span>`)
    }
  })
  
  return preview
}

const updatePreview = () => {
  // 更新 newDescriptor 以实时显示预览
  if (selectedOption.value && selectedOption.value.variables) {
    let result = selectedOption.value.template
    selectedOption.value.variables.forEach(variable => {
      const value = variableValues[variable]
      if (value && value.trim() !== '') {
        const regex = new RegExp(`\\{${variable}\\}`, 'g')
        result = result.replace(regex, value)
      }
    })
    newDescriptor.value = result
  }
}

// 检查是否可以添加描述符
const canAddDescriptor = computed(() => {
  if (!selectedOption.value) {
    return newDescriptor.value.trim() !== '' && !descriptors.value.includes(newDescriptor.value.trim())
  }

  // 检查是否有变量需要填写
  if (selectedOption.value.variables && selectedOption.value.variables.length > 0) {
    const emptyVariables = selectedOption.value.variables.filter(
      variable => !variableValues[variable] || variableValues[variable].trim() === ''
    )
    return emptyVariables.length === 0
  }
  
  return true
})

// 获取最终的描述符字符串
const getFinalDescriptor = () => {
  if (!selectedOption.value) {
    return newDescriptor.value.trim()
  }

  if (selectedOption.value.variables && selectedOption.value.variables.length > 0) {
    let finalDescriptor = selectedOption.value.template
    selectedOption.value.variables.forEach(variable => {
      const value = variableValues[variable] || ''
      const regex = new RegExp(`\\{${variable}\\}`, 'g')
      finalDescriptor = finalDescriptor.replace(regex, value)
    })
    return finalDescriptor
  } else {
    return selectedOption.value.template
  }
}

const addDescriptor = () => {
  if (!canAddDescriptor.value) {
    if (!selectedOption.value) {
      ElMessage.warning('请输入有效的描述符')
      return
    }
    
    // 检查是否有变量需要填写
    if (selectedOption.value.variables && selectedOption.value.variables.length > 0) {
      const emptyVariables = selectedOption.value.variables.filter(
        variable => !variableValues[variable] || variableValues[variable].trim() === ''
      )
      
      if (emptyVariables.length > 0) {
        ElMessage.warning(`请填写以下变量: ${emptyVariables.join(', ')}`)
        return
      }
    }
  }

  const finalDescriptor = getFinalDescriptor()
  
  if (!finalDescriptor || descriptors.value.includes(finalDescriptor)) {
    ElMessage.warning('描述符已存在或无效')
    return
  }

  descriptors.value.push(finalDescriptor)
  
  // 检查是否添加了 object 描述符，如果是则添加 label 描述符（不再自动同步fieldGroup）
  if (finalDescriptor === 'urn:alm:descriptor:com.tectonic.ui:object') {
    // 自动添加中文和英文标签描述符
    const fieldName = props.field.label || props.field.path || 'Field'
    const labelZhDescriptor = `urn:alm:descriptor:label:zh:${fieldName}`
    const labelEnDescriptor = `urn:alm:descriptor:label:en:${fieldName}`
    
    // 检查是否已存在，避免重复添加
    if (!descriptors.value.includes(labelZhDescriptor)) {
      descriptors.value.push(labelZhDescriptor)
    }
    if (!descriptors.value.includes(labelEnDescriptor)) {
      descriptors.value.push(labelEnDescriptor)
    }
  } else {
  }
  
  // 重置状态
  resetForm()
  
  // 不再立即保存，只是更新本地状态
}

// 重置表单状态
const resetForm = () => {
  newDescriptor.value = ''
  selectedOption.value = null
  Object.keys(variableValues).forEach(key => {
    delete variableValues[key]
  })
}

// 清除当前选择
const clearSelection = () => {
  resetForm()
}



const removeDescriptor = (index: number) => {
  descriptors.value.splice(index, 1)
}

const handleSelect = (option: any) => {
  // 如果是分组标题，不进行任何操作
  if (option.isGroupHeader) {
    return
  }
  
  selectedOption.value = option
  if (option.variables && option.variables.length > 0) {
    // 有变量的情况，显示变量编辑器
    newDescriptor.value = option.template
    // 延迟聚焦到第一个变量输入框
    nextTick(() => {
      const firstInput = document.querySelector('.variable-input .el-input__inner') as HTMLInputElement
      if (firstInput) {
        firstInput.focus()
      }
    })
  } else {
    // 没有变量的情况
    newDescriptor.value = option.template
  }
}

const handleInput = (val: string) => {
  const matchedOption = options.value.find(opt => opt.template === val)
  if (matchedOption) {
    selectedOption.value = matchedOption
  } else {
    selectedOption.value = null
  }
}

const handleEnterKey = () => {
  if (canAddDescriptor.value) {
    addDescriptor()
  }
}

const handleSave = () => {
  // 检查是否有未保存的输入
  if (selectedOption.value && selectedOption.value.variables && selectedOption.value.variables.length > 0) {
    const hasFilledVariables = selectedOption.value.variables.some(
      variable => variableValues[variable] && variableValues[variable].trim() !== ''
    )
    
    if (hasFilledVariables) {
      ElMessage.warning('您有未添加的描述符配置，请先点击"添加"按钮')
      return
    }
  } else if (newDescriptor.value.trim() !== '') {
    ElMessage.warning('您有未添加的描述符输入，请先点击"添加"按钮')
    return
  }

  // 保存更改并关闭对话框
  emit('save', {
    ...props.field,
    x_descriptors: descriptors.value,
    x_descriptor_count: descriptors.value.length
  })
  
  ElMessage.success('保存成功')
}

function formatTemplate(template: string, variables?: string[]) {
  if (!variables || variables.length === 0) {
    return `<span class="template-text">${template}</span>`
  }
  
  let result = template
  variables.forEach(variable => {
    result = result.replace(`{${variable}}`, `<span class="template-variable">{${variable}}</span>`)
  })
  return result
}

// 获取描述符的变量信息
const getDescriptorVariables = (descriptor: string) => {
  const opt = options.value.find(opt => descriptor.startsWith(opt.key) || (opt.template && descriptor.startsWith(opt.template.split('{')[0])))
  if (opt && opt.variables && opt.variables.length > 0) {
    const baseTemplate = opt.template.split('{')[0]
    const valuesPart = descriptor.substring(baseTemplate.length)
    const values = valuesPart.split(':').filter(v => v !== '')
    
    return opt.variables.map((variable, index) => ({
      name: variable,
      value: values[index] || ''
    }))
  }
  return []
}

// 开始编辑描述符
const startDescriptorEdit = (index: number) => {
  editingDescriptor.value = index
  const descriptor = descriptors.value[index]
  const variables = getDescriptorVariables(descriptor)
  
  // 清空之前的编辑值
  Object.keys(editingVariableValues).forEach(key => {
    delete editingVariableValues[key]
  })
  
  // 设置当前变量值
  variables.forEach(variable => {
    editingVariableValues[variable.name] = variable.value
  })
}

// 保存描述符编辑
const saveDescriptorEdit = (index: number) => {
  const descriptor = descriptors.value[index]
  const opt = options.value.find(opt => descriptor.startsWith(opt.key) || (opt.template && descriptor.startsWith(opt.template.split('{')[0])))
  
  if (opt && opt.variables && opt.variables.length > 0) {
    let newDescriptor = opt.template
    opt.variables.forEach(variable => {
      const value = editingVariableValues[variable] || ''
      newDescriptor = newDescriptor.replace(`{${variable}}`, value)
    })
    
    descriptors.value[index] = newDescriptor
  }
  
  cancelDescriptorEdit()
}

// 取消描述符编辑
const cancelDescriptorEdit = () => {
  editingDescriptor.value = null
  Object.keys(editingVariableValues).forEach(key => {
    delete editingVariableValues[key]
  })
}

// 带编辑功能的高亮显示
const highlightDescriptorWithEdit = (descriptor: string, index: number) => {
  const opt = options.value.find(opt => descriptor.startsWith(opt.key) || (opt.template && descriptor.startsWith(opt.template.split('{')[0])))
  if (opt && opt.variables && opt.variables.length > 0) {
    // 获取模板的基础部分（不包含变量的部分）
    const baseTemplate = opt.template.split('{')[0]
    
    // 提取实际值部分
    const valuesPart = descriptor.substring(baseTemplate.length)
    
    // 根据冒号分割获取实际值
    const values = valuesPart.split(':').filter(v => v !== '')
    
    // 构建高亮显示的结果
    let result = baseTemplate
    
    // 为每个变量添加对应的值或显示变量名
    if (opt.variables) {
      opt.variables.forEach((variable, varIndex) => {
        const actualValue = values[varIndex]
        if (actualValue && !actualValue.includes('{')) {
          // 已填写的变量值 - 绿色显示
          result += `<span class='descriptor-var descriptor-var-filled clickable-var' onclick='window.editDescriptorVariable(${index})'>${actualValue}</span>`
        } else {
          // 未填写的变量 - 黄色显示
          result += `<span class='descriptor-var descriptor-var-empty clickable-var' onclick='window.editDescriptorVariable(${index})'>{${variable}}</span>`
        }
        
        // 如果不是最后一个变量，添加冒号分隔符
        if (varIndex < opt.variables!.length - 1) {
          result += ':'
        }
      })
    }
    
    return result
  }
  return descriptor
}



// 设置全局函数
onMounted(() => {
  (window as any).editDescriptorVariable = startDescriptorEdit
})

onBeforeUnmount(() => {
  delete (window as any).editDescriptorVariable
})
</script>

<style lang="scss" scoped>
.descriptor-editor {
  .descriptor-list {
    max-height: 400px;
    overflow-y: auto;
    margin-bottom: 20px;
    .descriptor-card {
      margin-bottom: 10px;
      .card-content {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .descriptor-edit-mode {
          flex: 1;
          background: #f0f9ff;
          border: 1px solid #0284c7;
          border-radius: 8px;
          padding: 12px;
          
          .edit-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            
            .edit-title {
              font-weight: 600;
              color: #0369a1;
              font-size: 14px;
            }
            
            .edit-actions {
              display: flex;
              gap: 8px;
            }
          }
          
          .edit-variables {
            display: flex;
            flex-direction: column;
            gap: 8px;
            
            .edit-variable-item {
              :deep(.el-input-group__prepend) {
                background: #e0f2fe;
                border-color: #0284c7;
                
                .el-tag {
                  background: #0284c7;
                  color: white;
                  border: none;
                  font-family: monospace;
                  font-weight: 600;
                }
              }
              
              :deep(.el-input__inner) {
                border-left: none;
                font-family: monospace;
                
                &:focus {
                  border-color: #0284c7;
                  box-shadow: 0 0 0 2px rgba(2, 132, 199, 0.1);
                }
              }
            }
          }
        }
      }
    }
  }
  .add-descriptor {
    margin-bottom: 20px;
    position: relative;
    z-index: 10;
    
    .add-input-group {
      display: flex;
      gap: 10px;
      align-items: flex-start;
      
      .autocomplete-input {
        flex: 1;
        
        :deep(.el-input) {
          width: 100%;
        }
      }
      
      .el-button {
        flex-shrink: 0;
        height: 32px;
      }
    }
  }
  .variable-editor {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border: 2px solid #0284c7;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 4px 12px rgba(2, 132, 199, 0.1);
    
    .variable-editor-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      
      .header-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 600;
        color: #0369a1;
        font-size: 16px;
        
        .el-icon {
          font-size: 18px;
        }
      }
    }
    
    .variable-form {
      .variable-preview {
        background: white;
        border: 1px solid #cbd5e1;
        border-radius: 8px;
        padding: 12px;
        margin-bottom: 16px;
        
        .preview-label {
          font-weight: 600;
          color: #475569;
          margin-right: 8px;
        }
        
        .preview-content {
          font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
          font-size: 13px;
          color: #1e293b;
          display: block;
          margin: 8px 0;
          
          :deep(.variable-filled) {
            background: #10b981;
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: 600;
          }
          
          :deep(.variable-empty) {
            background: #f59e0b;
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: 500;
          }
        }
        
        .preview-status {
          display: flex;
          justify-content: flex-end;
          margin-top: 8px;
        }
      }
      
      .variable-inputs {
        display: flex;
        flex-direction: column;
        gap: 12px;
        
        .variable-input-item {
          .variable-form-item {
            margin-bottom: 0;
            
            :deep(.el-form-item__label) {
              font-weight: 600;
              color: #374151;
              min-width: 80px;
            }
            
            .variable-input {
              :deep(.el-input-group__prepend) {
                background: #f1f5f9;
                border-color: #cbd5e1;
                
                .el-tag {
                  background: #3b82f6;
                  color: white;
                  border: none;
                  font-family: monospace;
                  font-weight: 600;
                }
              }
              
              :deep(.el-input__inner) {
                border-left: none;
                font-family: monospace;
                
                &:focus {
                  border-color: #3b82f6;
                  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
                }
              }
            }
          }
        }
      }
    }
  }
  
  .descriptor-desc {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 20px;
    
    .desc-item {
      margin-bottom: 12px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .desc-label {
        font-weight: 600;
        color: #495057;
        margin-right: 8px;
      }
      
      .desc-content {
        color: #6c757d;
        line-height: 1.5;
        

      }
      
      .desc-example {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        padding: 8px 12px;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        font-size: 13px;
        color: #495057;
        display: block;
        margin-top: 4px;
        overflow-x: auto;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  
  // 自动完成选项样式
  .autocomplete-option {
    display: flex;
    flex-direction: column;
    gap: 8px;
    transition: all 0.3s ease;
    position: relative;
    
    &.has-variables {
      border-left: 3px solid var(--el-color-warning);
      background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
      border-radius: 6px;
      padding: 4px 8px;
      margin: 2px 0;
    }
    
    .option-header {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      gap: 8px;
      
      .option-template {
        font-weight: 600;
        font-size: 13px;
        line-height: 1.3;
        flex: 1;
        
        :deep(.template-text) {
          color: var(--el-text-color-primary);
        }
        
        :deep(.template-variable) {
          color: var(--el-color-success);
          background: var(--el-color-success-light-9);
          padding: 1px 4px;
          border-radius: 3px;
          font-weight: 600;
          font-size: 12px;
          border: 1px solid var(--el-color-success-light-5);
          margin: 0 1px;
          transition: all 0.3s ease;
        }
      }
      
      .option-badges {
        display: flex;
        gap: 4px;
        align-items: center;
        flex-shrink: 0;
        
        .variable-badge {
          background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
          color: white;
          border: none;
          font-weight: 700;
          font-size: 12px;
          padding: 4px 8px;
          border-radius: 8px;
          box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
          animation: glow-green 2s ease-in-out infinite alternate;
          
          .el-icon {
            margin-right: 3px;
            font-size: 13px;
          }
        }
        
        .type-badge {
          font-weight: 500;
          font-size: 11px;
        }
      }
    }
    
    .variables-display {
      display: flex;
      align-items: center;
      gap: 8px;
      background: rgba(255, 255, 255, 0.8);
      padding: 6px 8px;
      border-radius: 4px;
      border: 1px solid var(--el-color-warning-light-5);
      
      .variables-label {
        font-size: 11px;
        font-weight: 600;
        color: var(--el-color-warning-dark-2);
        flex-shrink: 0;
      }
      
      .variables-list {
        display: flex;
        gap: 4px;
        flex-wrap: wrap;
        
        .variable-tag {
          background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
          color: white;
          border: none;
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
          font-weight: 700;
          font-size: 11px;
          padding: 3px 6px;
          border-radius: 6px;
          box-shadow: 0 1px 4px rgba(103, 194, 58, 0.4);
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }
      }
    }
    
    .option-desc {
      font-size: 11px;
      color: var(--el-text-color-placeholder);
      line-height: 1.2;
      padding-left: 6px;
      border-left: 2px solid var(--el-border-color-extra-light);
      font-weight: 400;
      margin-top: 2px;
    }
    
    // 带变量选项的特殊样式
    &.has-variables .option-desc {
      border-left-color: var(--el-color-warning-light-3);
      color: var(--el-color-warning-dark-2);
    }
    

  }
}
// 主题和字体样式
.theme-default {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  color: #334155;
  border: 1px solid #cbd5e1;
  
  :deep(.el-card__body) {
    color: #334155;
  }
}

:deep(.descriptor-contrast) {
  font-family: 'Courier New', monospace;
  font-size: 15px;
}
:deep(.descriptor-var) {
  font-weight: bold;
  border-radius: 3px;
  padding: 2px 6px;
  margin: 0 2px;
  font-size: 12px;
  
  // 未填写的变量 - 橙色系
  &.descriptor-var-empty {
    color: #ea580c;
    background: #fed7aa;
    border: 1px solid #fb923c;
  }
  
  // 已填写的变量 - 深绿色底色白色字体
  &.descriptor-var-filled {
    color: white;
    background: #10b981;
    border: 1px solid #059669;
  }
  
  &.clickable-var {
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      transform: scale(1.05);
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
      
      &.descriptor-var-empty {
        background: #fb923c;
        color: white;
      }
      
      &.descriptor-var-filled {
        background: #059669;
        color: white;
      }
    }
  }
}
.delete-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: var(--el-color-danger);
  font-size: 16px;
  margin-right: 6px;
  cursor: pointer;
  border-radius: 50%;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);  
  width: 22px;
  height: 22px;
  
  &:hover {
    background: var(--el-color-danger-light-9);
    color: var(--el-color-danger-dark-2);
    transform: scale(1.1);
    box-shadow: 0 2px 8px var(--el-color-danger-light-3);
    
    .el-icon {
      transform: rotate(90deg);
    }
  }
  
  &:active {
    transform: scale(0.95);
  }
  
  .el-icon {
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }
}

// 动画定义
@keyframes glow-green {
  0% {
    box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
  }
  100% {
    box-shadow: 0 2px 12px rgba(103, 194, 58, 0.6);
  }
}

// 自动完成下拉框样式 - 使用全局样式覆盖
</style>

<style lang="scss">
/* 全局样式 - 自动完成组件优化 */
.descriptor-autocomplete-popper.el-popper {
  max-height: 400px;
  overflow-y: auto;
  
  .el-autocomplete-suggestion__list {
    padding: 8px;
    
    .el-autocomplete-suggestion__item {
      padding: 12px;
      margin-bottom: 8px;
      border-radius: 8px;
      border: 1px solid var(--el-border-color-light);
      background: var(--el-bg-color);
      transition: all 0.3s ease;
      position: relative;
      
      // 分组分隔线样式
      &:has(.group-divider) {
        padding: 0;
        background: none;
        border: none;
        margin: 8px 0 4px 0;
        cursor: default;
        
        &:hover {
          transform: none !important;
          box-shadow: none !important;
        }
        
        .group-divider {
          padding: 8px 12px 4px;
          border-top: 1px solid var(--el-color-primary-light-7);
          background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-color-primary-light-8) 100%);
          border-radius: 4px;
          
          .group-name {
            color: var(--el-color-primary);
            font-weight: 600;
            font-size: 12px;
          }
        }
      }
      
      // 组内选项的特殊样式
      &:has(.group-item) {
        margin-left: 16px;
        position: relative;
        
        &::before {
          content: '';
          position: absolute;
          left: -8px;
          top: 0;
          bottom: 0;
          width: 3px;
          background: var(--el-color-primary-light-5);
          border-radius: 2px;
        }
        
        .autocomplete-option {
          .option-badges {
            .group-badge {
              background: var(--el-color-success-light-8);
              color: var(--el-color-success);
              border: 1px solid var(--el-color-success-light-6);
              font-size: 11px;
            }
          }
        }
      }
      
      &:last-child {
        margin-bottom: 0;
      }
      
      // 带变量选项的特殊样式
      &:has(.has-variables) {
        border-color: var(--el-color-warning-light-5);
        background: linear-gradient(135deg, #fffef7 0%, #fefce8 100%);
        
        &::before {
          content: "🔧";
          position: absolute;
          top: 8px;
          right: 8px;
          font-size: 12px;
          opacity: 0.6;
        }
      }
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        
        &:has(.has-variables) {
          background: linear-gradient(135deg, var(--el-color-warning-light-9) 0%, var(--el-color-warning-light-8) 100%);
          border-color: var(--el-color-warning);
          box-shadow: 0 4px 12px var(--el-color-warning-light-7);
        }
        
        &:not(:has(.has-variables)) {
          background: var(--el-color-success-light-9);
          border-color: var(--el-color-success-light-5);
          box-shadow: 0 4px 12px var(--el-color-success-light-7);
        }
        
        .autocomplete-option {
          .option-header .option-template .template-text {
            color: var(--el-color-primary);
            font-weight: 600;
          }
          
          .option-header .option-template .template-variable {
            background: var(--el-color-success);
            color: white;
            transform: scale(1.1);
            border-color: var(--el-color-success);
            box-shadow: 0 1px 3px var(--el-color-success-light-5);
          }
          
          .option-desc {
            color: var(--el-text-color-regular);
            font-weight: 500;
          }
          
          .variables-display {
            background: rgba(255, 255, 255, 0.9);
            border-color: var(--el-color-warning);
            
            .variable-tag {
              background: var(--el-color-warning);
              transform: scale(1.05);
            }
          }
        }
      }
      
      &.highlighted {
        transform: translateY(-2px);
        border-color: var(--el-color-primary);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
        
        &:has(.has-variables) {
          background: linear-gradient(135deg, var(--el-color-warning-light-8) 0%, var(--el-color-warning-light-6) 100%);
          border-color: var(--el-color-warning);
          box-shadow: 0 6px 16px var(--el-color-warning-light-5);
        }
        
        &:not(:has(.has-variables)) {
          background: linear-gradient(135deg, var(--el-color-success-light-8) 0%, var(--el-color-success-light-6) 100%);
          border-color: var(--el-color-success);
          box-shadow: 0 6px 16px var(--el-color-success-light-5);
        }
        
        .autocomplete-option {
          .option-header .option-template .template-text {
            color: var(--el-color-primary);
            font-weight: 700;
          }
          
          .option-header .option-template .template-variable {
            background: var(--el-color-success);
            color: white;
            transform: scale(1.15);
            border-color: var(--el-color-success);
            box-shadow: 0 2px 8px var(--el-color-success-light-4);
          }
          
          .option-desc {
            color: var(--el-text-color-regular);
            font-weight: 600;
          }
          
          .variables-display {
            background: white;
            border-color: var(--el-color-warning);
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
            
            .variable-tag {
              background: var(--el-color-warning);
              transform: scale(1.1);
              box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
            }
          }
        }
      }
    }
  }
}
</style>
 